package cn.edu.cuc.yjsy.admin.views;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.viewers.IOpenListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
import org.eclipse.ui.part.ViewPart;
import org.osgi.framework.Bundle;

import cn.edu.cuc.yjsy.admin.Activator;
import cn.edu.cuc.yjsy.admin.util.ILogger;
import cn.edu.cuc.yjsy.admin.util.LoggerAdvisor;
import cn.edu.cuc.yjsy.report.Report;
import cn.edu.cuc.yjsy.report.ReportElement;
import cn.edu.cuc.yjsy.report.ReportFolder;
import cn.edu.cuc.yjsy.report.ReportItem;
import cn.edu.cuc.yjsy.report.ReportModelManager;
import cn.edu.cuc.yjsy.report.ReportRoot;

public class ReportNavigatorView extends ViewPart {
	
	class ViewContentProvider implements IStructuredContentProvider,
			ITreeContentProvider {

		public Object[] getElements(Object inputElement) {
			return getChildren(inputElement);
		}

		public void dispose() {
			// TODO Auto-generated method stub
			
		}

		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
			// TODO Auto-generated method stub
			
		}

		public Object[] getChildren(Object parentElement) {
			if(parentElement instanceof ReportFolder){
				return ((ReportFolder)parentElement).getReports().toArray(new Object[0]);
			}else if(parentElement instanceof ReportRoot)
				return ((ReportRoot)parentElement).getFolders().toArray(new Object[0]);
			return null;
		}

		public Object getParent(Object element) {
			if(element instanceof ReportItem)
				return ((ReportItem)element).getParent();
			return null;
		}

		public boolean hasChildren(Object element) {
			if(element instanceof Report)
				return false;
			else if(element instanceof ReportFolder)
				return ((ReportFolder)element).getReports().size() > 0;
			return false;
		}

	}

	class ViewLabelProvider extends LabelProvider {
		public String getText(Object obj) {
			return ((ReportElement)(obj)).getName();
		}
		public Image getImage(Object obj) {
			String imageKey = ISharedImages.IMG_OBJ_ELEMENT;
			if (obj instanceof ReportFolder)
			   imageKey = ISharedImages.IMG_OBJ_FOLDER;
			return PlatformUI.getWorkbench().getSharedImages().getImage(imageKey);
		}
	}

	private static ILogger logger = new LoggerAdvisor(ReportNavigatorView.class);
	public static final String ID = "cn.edu.cuc.yjsy.admin.reportView";
	private ReportModelManager rpManager;
	private ReportRoot root;
	private TreeViewer viewer;
	
	public ReportNavigatorView() {
    	try {
			rpManager = new ReportModelManager();
			Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID);
			String configFile = null;
			if (bundle != null) {
				IPath path = null;
				path = new Path(FileLocator.toFileURL(bundle.getEntry("/"))
						.getPath());
				configFile = path.toOSString() + File.separator + "report.xml";

				rpManager.load(new Path(configFile));
				root = rpManager.getModel();
			}
		} catch (IOException e) {
			logger.error("Error to load reporting configuration.");
			e.printStackTrace();
		}    	
	}

	public void createPartControl(Composite parent) {
		viewer = new TreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
		viewer.setContentProvider(new ViewContentProvider());
		viewer.setLabelProvider(new ViewLabelProvider());
		viewer.setInput(root);
		viewer.expandAll();
		viewer.addOpenListener(new IOpenListener(){
			public void open(OpenEvent event) {
				if(event.getSelection() instanceof IStructuredSelection){
					Report rp = (Report)((IStructuredSelection)event.getSelection()).getFirstElement();
					IWorkbenchBrowserSupport support = PlatformUI
						.getWorkbench().getBrowserSupport();
					try {
						support.createBrowser(IWorkbenchBrowserSupport.STATUS,
							rp.getName(), null, null).openURL(new URL(rp.getUrl()));
					} catch (PartInitException e) {
						logger.error("Error to open internal browser.");
						e.printStackTrace();
					} catch (MalformedURLException e) {
						logger.error("Invalid url: " + rp.getUrl());
						e.printStackTrace();
					}
				}
			}			
		});
	}

	public void setFocus() {
		viewer.getControl().setFocus();
	}
}
